<template>
  <div class="app-container customer-div" style="overflow-x: auto">
    <!-- tabs标签页  -->
    <el-tabs v-model="listQuery.groupBy" type="card" @tab-click="handleClick1">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="军团" name="department"></el-tab-pane>
      <el-tab-pane label="业务员" name="inquiryUser"></el-tab-pane>
      <el-tab-pane label="我的" name="my"></el-tab-pane>
    </el-tabs>
    <!-- 搜索栏  -->
    <el-form :inline="true" :model="listQuery" size="mini" label-width="50px">
      <el-form-item label="日期：">
        <el-date-picker
          v-model="listQuery.inquiryDate"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="" label-width="0px">
        <el-radio-group v-model="listQuery.groupDate">
          <el-radio-button label="day">按日</el-radio-button>
          <el-radio-button label="month">按月</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        label="军团:"
        label-width="50px"
        v-if="listQuery.groupBy == 'department'"
      >
        <el-cascader
          v-model="listQuery.departmentId"
          :options="data2"
          filterable
          @focus="getBuMenList"
          :props="{
            checkStrictly: true,
            value: 'departmentId',
            label: 'departmentName',
            emitPath: false,
          }"
          clearable
        >
        </el-cascader>
      </el-form-item>

      <el-form-item
        label="业务员:"
        label-width="70px"
        v-if="listQuery.groupBy == 'inquiryUser'"
      >
        <el-select
          v-model="listQuery.inquiryUserId"
          placeholder="请选择"
          allow-create
          @focus="getSalesmanList"
          filterable
          clearable
        >
          <el-option
            v-for="item in salesMemberList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
            :loading="salesmanLoading"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          style="margin-left: 10px"
          type="primary"
          @click="getSettleReport"
        >
          查询
        </el-button>
        <el-button
          :loading="btnLoading"
          style="margin-left: 10px"
          @click="downloadExcel"
          type="primary"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 卡片 -->
    <el-card class="box-card">
      <div>
        <p class="inquiryNumber">{{ cardTotal.inquiryCountTotal }}</p>
        <span class="inquiryStr">询盘数量</span>
      </div>
      <div>
        <p class="inquiryNumber">{{ cardTotal.priceCountTotal }}</p>
        <span class="inquiryStr">报价数量</span>
      </div>
      <div>
        <p class="inquiryNumber">{{ cardTotal.orderCountTotal }}</p>
        <span class="inquiryStr">下单数量</span>
      </div>
      <div>
        <p class="inquiryNumber">{{ cardTotal.orderPayCountTotal }}</p>
        <span class="inquiryStr">付款数量</span>
      </div>
      <div>
        <p class="inquiryNumber">{{ cardTotal.orderSendCountTotal }}</p>
        <span class="inquiryStr">已发货数量</span>
      </div>
      <div>
        <p class="inquiryNumber">{{ cardTotal.conversionRateTotal }}</p>
        <span class="inquiryStr">询盘成交转换率</span>
      </div>
    </el-card>
    <!-- echarts图标 -->
    <div
      id="settleChart"
      style="height: 500px; margin-top: 20px"
      v-loading="loadingChart"
    ></div>
    <!-- 数据列表 -->
    <el-table
      :data="tableData"
      style="width: 98%; margin-top: 20px"
      border
      height="500"
      :default-sort="{
        prop: [
          'inquiryCount',
          'inquiryNum',
          'priceNum',
          'orderCount',
          'orderNum',
          'orderPayNum',
        ],
        order: 'descending',
      }"
      :header-cell-style="{ background: '#fafafa', height: '48px', padding: 0 }"
    >
      <el-table-column
        v-if="listQuery.groupDate == 'day'"
        prop="inquiryDate"
        label="日期"
        min-width="120"
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-if="listQuery.groupDate == 'month'"
        prop="inquiryDate"
        label="月份"
        min-width="120"
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-if="listQuery.groupBy == 'inquiryUser'"
        prop="inquiryUser"
        label="业务员"
        min-width="130"
        align="center"
      >
      </el-table-column>
      <el-table-column
        v-if="listQuery.groupBy == 'department'"
        prop="departmentName"
        label="军团"
        min-width="130"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="inquiryCount"
        label="询盘次数"
        sortable
        min-width="120"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="inquiryNum"
        label="询盘数量"
        sortable
        min-width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="cancelCount"
        label="取消次数"
        min-width="100"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="priceCount"
        label="报价次数"
        min-width="100"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="priceNum"
        label="报价数量"
        sortable
        min-width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="orderCount"
        label="成交次数"
        sortable
        min-width="100"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="orderNum"
        label="成交量"
        sortable
        min-width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="orderPayNum"
        label="付款数量"
        sortable
        min-width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="orderSendCount"
        label="已发货数"
        min-width="150"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="conversionRate"
        label="询盘成交转化率"
        min-width="160"
        align="center"
      >
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
const defaultListQuery = {
  groupBy: "all", //分组：department 部门 inquiryUser 业务员 my 我的
  groupDate: "day", //时间分组：day 按年月日分组 month 按年月分组
  inquiryDate: [], //搜索时间段
  inquiryUserId: "", //业务员id
  departmentId: "", //部门id
  orderBy: "", // 排序 ：inquiryCountDesc 询价次数降序 inquiryCountAsc
  // 询价次数升序 inquiryNumDesc询价数量降序 inquiryNumAsc询价数量升序
  // priceCountDesc报价次数降序 priceCountAsc报价次数升序 priceNumDesc报价数量降序
};
import {getOrderUsersList} from '@/api/partner'
import {getDeptList} from '@/api/management'
import { getSettleReportAPI } from "@/api/allInLine/report.js"; //成交列表
import { mapGetters } from "vuex";
import { formatDate } from "@/utils/date";
import echarts from "echarts";
export default {
  name: "settleReport",
  data() {
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "7天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "30天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      btnLoading: false,
      loadingChart: false,
      // 卡片数据
      cardTotal: {},
      // 表格数据
      tableData: [],
      optionsLoading: false,
      // 业务员列表
      salesMemberList: [],
      salesmanLoading: false,
      // 军团列表
      data2: [],
      dataLoading: false,
    };
  },
  computed: {
    ...mapGetters(["name", "mobile", "userId"]),
  },
  created() {
    let now = new Date();
    let today = formatDate(now, "yyyy-MM-dd");
    this.listQuery.inquiryDate = [today, today];
    this.getSettleReport();
  },
  mounted() {
    this.initChart();
  },
  methods: {
    //获取部门列表
    getBuMenList() {
      this.dataLoading = false;
      getDeptList().then((res) => {
        this.data2 = this.forTree(res);
        this.dataLoading = false;
      });
    },
    //去除不要的children
    forTree(list) {
      let newList = list;
      if (newList.length) {
        for (let i = 0; i < newList.length; i++) {
          if (newList[i].child_cates && newList[i].child_cates.length > 0) {
            this.forTree(newList[i].child_cates);
          } else {
            delete newList[i].child_cates;
          }
        }
        return newList;
      }
    },
    // 获取业务员列表
    async getSalesmanList() {
      this.salesmanLoading = true;
      const res = await getOrderUsersList({ departmentType: "" });
      this.salesMemberList = res;
      this.salesmanLoading = false;
    },
    // 配置图表
    initChart() {
      const chart = echarts.init(document.getElementById("settleChart"));
      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{b} : {c}",
        },
        legend: {
          data: ["询盘数量", "报价数", "下单数", "付款数", "已发货"],
        },
        series: [
          {
            name: "Funnel",
            type: "funnel",
            left: "10%",
            top: 40,
            bottom: 0,
            width: "80%",
            min: 0,
            max: 100,
            minSize: "0%",
            maxSize: "100%",
            sort: "descending",
            gap: 2,
            label: {
              show: true,
              position: "inside",
            },
            labelLine: {
              length: 10,
              lineStyle: {
                width: 1,
                type: "solid",
              },
            },
            itemStyle: {
              borderColor: "#fff",
              borderWidth: 1,
            },
            emphasis: {
              label: {
                fontSize: 20,
              },
            },
            data: [
              { value: this.cardTotal.inquiryCountTotal, name: "询盘数" },
              { value: this.cardTotal.priceCountTotal, name: "报价数" },
              { value: this.cardTotal.orderCountTotal, name: "下单数" },
              { value: this.cardTotal.orderPayCountTotal, name: "付款数" },
              { value: this.cardTotal.orderSendCountTotal, name: "已发货" },
            ],
          },
        ],
      };
      chart.setOption(option);
    },
    //获取成交统计列表
    async getSettleReport() {
      this.loadingChart = true;
      const res = await getSettleReportAPI(this.listQuery);
      this.cardTotal = res.total;
      this.tableData = res.list;
      this.initChart();
      this.loadingChart = false;
    },
    // tab栏切换
    handleClick1() {
      this.listQuery.inquiryUserId = "";
      this.listQuery.departmentId = "";
      this.getSettleReport();
    },
    //下载excle
    downloadExcel() {
      let params = JSON.parse(JSON.stringify(this.listQuery));
      params.isExport = 1;
      this.btnLoading = true;
      getSettleReportAPI(params)
        .then((res) => {
          this.btnLoading = false;
          require.ensure([], () => {
            const { export_json_to_excel } = require("sheet/Export2Excel");
            const tHeader = res.title;
            const filterVal = res.columns;
            const list = res.list;
            const data = this.formatJson(filterVal, list);
            export_json_to_excel(tHeader, data, res.fileName);
          });
        })
        .catch(() => {
          this.btnLoading = false;
        });
    },
    //下载表格数据格式化
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
  },
};
</script>

<style scoped lang="scss">
.el-card /deep/ .el-card__body {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 90px;
  .inquiryNumber {
    text-align: center;
    font-size: 18px;
    font-weight: 500;
  }
  .inquiryStr {
    font-size: 14px;
    color: #ccc;
  }
}
</style>
